#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string>
#include <cstring>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
void Usage(const string &proc)
{
    cout << "\n\tUsag:" << proc << " ip port" << endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);
    while (true)
    {
        int cnt = 5;
        bool isconnect = false;
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            cerr << "sockfd error" << endl;
            return 1;
        }
        do
        {
            int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                cerr << "reconnect,cnt:" << cnt << endl;
                isconnect = true;
                cnt--;
                close(sockfd);
                sleep(1);
            }
            else
            {
                break;
            }
        } while (cnt && isconnect);
        if (cnt == 0)
        {
            cout << "user quit..." << endl;
            break;
        }
        string message;
        char inbuff[4096];

        cout << "please enter#";
        getline(cin, message);
        ssize_t n = write(sockfd, message.c_str(), message.size());
        // cout << sockfd << endl;
        if (n <= 0)
        {
            cout << "---------------" << endl;
            cout << "write error,reconnect" << endl;
            close(sockfd);
            continue;
        }

        n = read(sockfd, inbuff, sizeof(inbuff));
        if (n > 0)
        {
            inbuff[n] = 0;
            cout << inbuff << endl;
        }

        close(sockfd);
    }

    return 0;
}